using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Xml;

namespace Pay.Core.AlipayWap {
	/// <summary>
	/// 功能：支付宝各接口请求提交类
	/// 详细：构造支付宝各接口表单HTML文本，获取远程HTTP数据
	/// </summary>
	public class Submit {
		#region 字段
		//支付宝网关地址（新）
		private string GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
		//MD5安全检验码,RSA是商户的私钥
		private string _private_key = "";
		//编码格式
		private string _input_charset = "utf-8";
		//签名方式
		private string _sign_type = "";
		#endregion
		private payment_query _payment_query;

		public Submit(payment_query payment_query) {
			_payment_query = payment_query;
			_sign_type = _payment_query.key.Trim().ToUpper();
			if (_sign_type == "MD5")
				_private_key = _payment_query.app_secret;
			else if (_sign_type == "RSA")
				_private_key = HttpContext.Current.Server.MapPath("~/App_Data/key/rsa_private_key.pem");
		}

		/// <summary>
		/// 生成请求时的签名
		/// </summary>
		/// <param name="sPara">请求给支付宝的参数数组</param>
		/// <returns>签名结果</returns>
		private string BuildRequestMysign(Dictionary<string, string> sPara) {
			//把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
			string prestr = Core.CreateLinkString(sPara);

			//把最终的字符串签名，获得签名结果
			string mysign = "";
			switch (_sign_type) {
				case "RSA":
					mysign = RSAFromPkcs8.sign(prestr, _private_key, _input_charset);
					break;
				case "MD5":
					mysign = AlipayMD5.Sign(prestr, _private_key, _input_charset);
					break;
				default:
					mysign = "";
					break;
			}

			return mysign;
		}

		/// <summary>
		/// 生成要请求给支付宝的参数数组
		/// </summary>
		/// <param name="sParaTemp">请求前的参数数组</param>
		/// <returns>要请求的参数数组</returns>
		private Dictionary<string, string> BuildRequestPara(SortedDictionary<string, string> sParaTemp) {
			//待签名请求参数数组
			Dictionary<string, string> sPara = new Dictionary<string, string>();
			//签名结果
			string mysign = "";

			//过滤签名参数数组
			sPara = Core.FilterPara(sParaTemp);

			//获得签名结果
			mysign = BuildRequestMysign(sPara);

			//签名结果与签名方式加入请求提交参数组中
			sPara.Add("sign", mysign);
			sPara.Add("sign_type", _sign_type);

			return sPara;
		}

		/// <summary>
		/// 生成要请求给支付宝的参数数组
		/// </summary>
		/// <param name="sParaTemp">请求前的参数数组</param>
		/// <param name="code">字符编码</param>
		/// <returns>要请求的参数数组字符串</returns>
		private string BuildRequestParaToString(SortedDictionary<string, string> sParaTemp, Encoding code) {
			//待签名请求参数数组
			Dictionary<string, string> sPara = new Dictionary<string, string>();
			sPara = BuildRequestPara(sParaTemp);

			//把参数组中所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对参数值做urlencode
			string strRequestData = Core.CreateLinkStringUrlencode(sPara, code);

			return strRequestData;
		}

		/// <summary>
		/// 建立请求，以表单HTML形式构造（默认）
		/// </summary>
		/// <param name="sParaTemp">请求参数数组</param>
		/// <returns>提交表单HTML文本</returns>
		public string BuildRequest(SortedDictionary<string, string> sParaTemp) {
			//待请求参数数组
			Dictionary<string, string> dicPara = new Dictionary<string, string>();
			dicPara = BuildRequestPara(sParaTemp);
			string url = GATEWAY_NEW + "_input_charset=" + _input_charset;
			string para = string.Empty;
			foreach (KeyValuePair<string, string> temp in dicPara) {
				para += "&" + temp.Key + "=" + temp.Value;
			}
			return url + para;
		}



		/// <summary>
		/// 用于防钓鱼，调用接口query_timestamp来获取时间戳的处理函数
		/// 注意：远程解析XML出错，与IIS服务器配置有关
		/// </summary>
		/// <returns>时间戳字符串</returns>
		public string Query_timestamp() {
			string url = GATEWAY_NEW + "service=query_timestamp&partner=" + _payment_query.mchid + "&_input_charset=" + _input_charset;
			string encrypt_key = "";

			XmlTextReader Reader = new XmlTextReader(url);
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(Reader);

			encrypt_key = xmlDoc.SelectSingleNode("/alipay/response/timestamp/encrypt_key").InnerText;

			return encrypt_key;
		}
	}
}
